//
//  XZLeftTicketController.m
//  生活小助手
//
//  Created by lixiangzhou on 14-8-8.
//  Copyright (c) 2014年 lxz. All rights reserved.
//

#import "XZLeftTicketController.h"
#import "XZLTParam.h"
#import "XZLTResult.h"
#import "XZLTTrain.h"
#import "XZFunctionKey.h"
#import "MBProgressHUD+MJ.h"
#import "XZTrainTool.h"
#import "XZLTCell.h"
#import "XZLTTrain.h"
#import "XZTrainController.h"
#import "XZTrainNumController.h"


#define kFieldWidth 80

@interface XZLeftTicketController () <UITableViewDataSource, UITableViewDelegate, UITextFieldDelegate>
@property (weak, nonatomic) UIView *topView;
@property (weak, nonatomic) UITextField *startStationField;
@property (weak, nonatomic) UITextField *endStationField;
@property (strong, nonatomic) NSArray *results;
@property (assign, nonatomic) BOOL netOK;
@property (weak, nonatomic) UITableView *tableView;
@property (weak, nonatomic) UITextField *dateField;
@end

@implementation XZLeftTicketController
- (UITableView *)tableView
{
    if (!_tableView) {
        UITableView *tableView = [[UITableView alloc] init];
        tableView.sectionHeaderHeight = kTrainSectionHeaderHeight;
        tableView.rowHeight = kTrainRowHeight;
        tableView.width = self.view.width;
        tableView.height = self.view.height - CGRectGetMaxY(self.topView.frame);
        tableView.y = self.view.height - tableView.height;
        tableView.bounces = NO;
        tableView.delegate = self;
        tableView.dataSource = self;
        [self.view addSubview:tableView];
        _tableView = tableView;
    }
    return _tableView;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.view.backgroundColor = kGlobalBackgroundColor;
    self.view.y = 93;
    self.view.height = kScreenHeight - self.view.y;
    [self addViews];

}


- (void)addViews
{
    /* ------------------顶部的查找------------------*/
    UIView *topView = [[UIView alloc] init];
    CGFloat topRowHeight = 30;
    topView.y = kMargin;
    [self.view addSubview:topView];
    self.topView = topView;
    
    /* ------------------始发站------------------*/
    UILabel *label = [[UILabel alloc] init];
    label.font = kTrainNormalFont;
    label.text = @"始发站：";
    CGSize size = [label.text sizeWithAttributes:@{NSFontAttributeName: label.font}];
    label.width = size.width;
    label.height = topRowHeight;
    [topView addSubview:label];
    
    UITextField *startStationField = [UITextField textFieldWithPlaceholder:@"如北京" leftMargin:5];
    startStationField.font = kTrainNormalFont;
    startStationField.x = CGRectGetMaxX(label.frame);
    startStationField.width = kFieldWidth;
    startStationField.height = label.height;
    self.startStationField = startStationField;
    [topView addSubview:startStationField];
    
    /* ------------------终点站------------------*/
    UILabel *label2 = [[UILabel alloc] init];
    label2.font = kTrainNormalFont;
    label2.text = @"终点站：";
    CGSize size2 = [label2.text sizeWithAttributes:@{NSFontAttributeName: label2.font}];
    label2.width = size2.width;
    label2.height = topRowHeight;
    label2.x = CGRectGetMaxX(startStationField.frame) + kMargin;
    [topView addSubview:label2];
    
    UITextField *endStationField = [UITextField textFieldWithPlaceholder:@"如江西" leftMargin:5];
    endStationField.font = kTrainNormalFont;
    endStationField.x = CGRectGetMaxX(label2.frame);
    endStationField.width = kFieldWidth;
    endStationField.height = label.height;
    self.endStationField = endStationField;
    [topView addSubview:endStationField];
    
    /* ------------------日期------------------*/
    UIView *dateView = [[UIView alloc] init];
    dateView.y = CGRectGetMaxY(startStationField.frame) + kMargin;
    [topView addSubview:dateView];
    
    UILabel *label3 = [[UILabel alloc] init];
    label3.font = kTrainNormalFont;
    label3.text = @"选择日期：";
    CGSize size3 = [label3.text sizeWithAttributes:@{NSFontAttributeName: label3.font}];
    label3.width = size3.width;
    label3.height = topRowHeight;
    [dateView addSubview:label3];
    
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd";
    
    UITextField *dateField = [UITextField textFieldWithPlaceholder:@"" leftMargin:5];
    dateField.text = [df stringFromDate:[[NSDate alloc] init]];
    dateField.clearButtonMode = UITextFieldViewModeNever;
    dateField.width = 100;
    dateField.height = topRowHeight;
    dateField.x = CGRectGetMaxX(label3.frame) + kMargin;
    dateField.delegate = self;
    dateField.font = kTrainNormalFont;
    self.dateField = dateField;
    
    UIDatePicker *datePicker = [[UIDatePicker alloc] init];
    datePicker.datePickerMode = UIDatePickerModeDate;
    datePicker.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
    [datePicker addTarget:self action:@selector(selectDate:) forControlEvents:UIControlEventValueChanged];
    dateField.inputView = datePicker;
    
    [dateView addSubview:dateField];

    dateView.height = topRowHeight;
    dateView.width = CGRectGetMaxX(dateField.frame) + CGRectGetMinX(label3.frame);
    dateView.centerX = self.view.centerX;
    
    topView.width = CGRectGetMaxX(endStationField.frame) - CGRectGetMinX(label.frame);
    topView.centerX = self.view.centerX;
    
    UIButton *queryBtn = [[UIButton alloc] init];
    [queryBtn setTitle:@"查询" forState:UIControlStateNormal];
    [queryBtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    queryBtn.backgroundColor = [UIColor orangeColor];
    queryBtn.height = topRowHeight;
    queryBtn.width = topView.width;
    queryBtn.y = CGRectGetMaxY(dateView.frame) + kMargin;
    [queryBtn addTarget:self action:@selector(getTrains) forControlEvents:UIControlEventTouchUpInside];
    [topView addSubview:queryBtn];
    
    topView.height = CGRectGetMaxY(queryBtn.frame);
}

- (void)selectDate:(UIDatePicker *)datePicker
{
    NSDateFormatter *df = [[NSDateFormatter alloc] init];
    df.dateFormat = @"yyyy-MM-dd";
    self.dateField.text = [df stringFromDate:datePicker.date];
    self.dateField.enabled = YES;
}

- (void)getTrains
{
    NSString *start = self.startStationField.text;
    NSString *end = self.endStationField.text;
    XZLTParam *param = [[XZLTParam alloc] init];
    param.from = start;
    param.to = end;
    param.date = self.dateField.text;
    param.key = [XZFunctionKey trainKey];
    
    [MBProgressHUD showMessage:@"正在帮您查询"];
    [XZTrainTool leftTicketWithParameter:param success:^(XZLTResult *responseObj) {
        self.netOK = YES;
        [self processResponse:responseObj];
        [MBProgressHUD hideHUD];
    } failure:^(NSError *error) {
        self.netOK = YES;
        [MBProgressHUD hideHUD];
        [MBProgressHUD showError:error.domain];
    }];
    
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(5.0 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
        if (!self.netOK) {
            [MBProgressHUD hideHUD];
            [MBProgressHUD showError:@"请检查您的网络"];
        }
    });
    [self.view endEditing:YES];
}

- (void)processResponse:(XZLTResult *)result
{
    self.results = result.result;
    
    [self.tableView reloadData];
}


#pragma mark - UITableViewDataSource, UITableViewDelegate
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    XZLTCell *cell = [XZLTCell cellWithTableView:tableView];
    XZLTTrain *train = self.results[indexPath.row];
    cell.train = train;
    return cell;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.results.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 90;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    XZTrainController *trainController = (XZTrainController *)[self parentViewController];
    XZTrainNumController *trainNumController = trainController.controllerDict[@(XZTrainSubControllerTypeTrainNum)];
    XZLTTrain *train = self.results[indexPath.row];
    trainNumController.trainNo = train.train_no;
    trainController.segementControl.selectedSegmentIndex = XZTrainSubControllerTypeTrainNum;
    [trainController changeValue:trainController.segementControl];
}

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}

@end
